package com.dayouzi.crawler_monitor.service.impl;

import com.dayouzi.crawler_monitor.base.exception.Assert;
import com.dayouzi.crawler_monitor.base.result.ResponseEnum;
import com.dayouzi.crawler_monitor.mapper.UserAdminMapper;
import com.dayouzi.crawler_monitor.pojo.entity.UserAdmin;
import com.dayouzi.crawler_monitor.pojo.query.LoginQuery;
import com.dayouzi.crawler_monitor.pojo.vo.LoginVO;
import com.dayouzi.crawler_monitor.service.LoginService;
import com.dayouzi.crawler_monitor.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DaYouZi
 * @since 2023-03-06
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserAdminMapper userAdminMapper;

    @Override
    public LoginVO login(LoginQuery loginQuery) {
        String userName = loginQuery.getUsername();
        String password = loginQuery.getPassword();

        //从数据库获取用户信息
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);

        //判断用户是否存在
        Assert.notNull(userAdmin, ResponseEnum.LOGIN_MOBILE_ERROR);

        //判断密码是否正确
        Assert.equals(password, userAdmin.getPassword(), ResponseEnum.LOGIN_PASSWORD_ERROR);

        //记录用户登录日志
        //TODO

        //生成token
        String token = JwtUtils.createToken(Long.valueOf(userAdmin.getId()), userAdmin.getUserName());
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        return loginVO;
    }

    @Override
    public String[] getRole(String userName) {
        //从数据库获取用户信息
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);
        String roleName = "";
        Integer roleCode = userAdmin.getRole();
        String[] result = new String[2];
        switch (roleCode) {
            case 0:
                result[0] = "admin";
                result[1] = userName;
                break;
            case 1:
                result[0] = userName;
                break;
            default:
                break;
        }
        return result;
    }

    @Override
    public Integer getId(String userName) {
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);
        return userAdmin.getId();
    }

    @Override
    public String getPerson(String userName) {
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);
        return userAdmin.getPerson();
    }

    @Override
    public Integer getNoticeStatus(String userName) {
        UserAdmin userAdmin = userAdminMapper.getInfoByUserName(userName);
        return userAdmin.getNoticeStatus();
    }
}
